import {deepFullCopy, messages} from "share/common";
import React from 'react'
import config from 'config'
import httpFetch from 'share/httpFetch'
import { Form, Row, Col, Popover, Input, Button, Tag, message, Spin, Dropdown, Menu, Icon, Alert, Checkbox, Modal, Popconfirm } from 'antd'
const FormItem = Form.Item;
const { CheckableTag } = Tag;
import ApproveTransfer from 'components/template/approve-transfer'
import ApproveAdditional from 'components/template/approve-additional'
import ListSelector from 'components/list-selector'
import AdminSkip from 'containers/setting/process-monitoring-platform/admin-skip/admin-skip'
import 'styles/components/template/approve-bar.scss'
import chooserData from 'share/chooserData'
import baseService from 'share/base.service'
import {connect} from "react-redux";
const { TextArea } = Input;
import adminApproveListService from 'containers/setting/process-monitoring-platform/admin-approve-list.service'

class ApproveBar extends React.Component{
  constructor(props) {
    super(props);
    this.state = {
      loading: false,
      tags: [],
      fastReplyEdit: false,
      popoverVisible: false,
      inputVisible: false,
      inputValue: '',
      fastReplyChosen: [],
      inputError: false,
      errorMessage: "",
      showAdditionalSelector: false,
      additionalNames: [], //加签人的Name
      additionalItems: [],
      priceAuditor: false,
      isShowBigTextArea: false,
      showAdminSkipModal:false,
      honestEvent: [],
      disablePress:false,
      skipLoading: false,
      transferVisible: false, //审批转交的modal的visible属性
      additionalVisible: false, //审批加签的第二个modal的visible属性
    }
  }

  componentWillMount() {
    this.getQuickTags()
  }

  //获取快捷回复内容
  getQuickTags = () => {
    this.setState({ loading: true });
    let url='/api/quick/reply';
    if(this.props.audit){
      url=`/api/audit/quick/reply?userOid=${this.props.user.userOID}`;
    }
    httpFetch.get(`${config.baseUrl}${url}`).then(res => {
      if(res.status === 200) {
        let tags = this.props.audit ? res.data.rows : res.data;
        this.setState({ tags: tags, loading: false })
      }
    })

  };

  //显示新增快捷回复输入框
  showTagInput = () => {
    this.setState({ inputVisible: true });
  };
  //关闭新增快捷回复输入框
  closeInputModal = () => {
    this.setState({ inputVisible: false, popoverVisible: true });
  };

  //popover的visible控制
  handleVisibleChange = (visible) => {
    if(['/main/financial-management/finance-audit/prending_audit'].includes(this.props.backUrl)){
      this.setState({ popoverVisible: false });
    }else{
      this.setState({ popoverVisible: visible });
    }
  };

  //关闭popover
  handleClosePopover = () => {
    this.setState({ popoverVisible: false });
  };

  //选择快捷回复
  onFastReplyChange = (checked, id) => {
    const { getFieldsValue, setFieldsValue } = this.props.form;
    let { tags, fastReplyChosen, honestEvent } = this.state;
    let fastReplyChosenValue = [];
    if (getFieldsValue().reason) {
      fastReplyChosenValue.push(getFieldsValue().reason);
      fastReplyChosenValue = fastReplyChosenValue[0].split('，')
    }
    tags.map(item => {
      if (item.id === id) {
        item.checked = true;
        fastReplyChosen.push(item);
        fastReplyChosenValue.push(item.reply)
      }
    });
    setFieldsValue({ reason: fastReplyChosenValue.join('，') });
    this.setState({
      fastReplyChosen,
      inputError: fastReplyChosenValue.join('，').length > 500,
      errorMessage: messages('common.max.characters.length', {max: 500})
    }, () => {
      let {needHonest,applicantOID,jobId} = this.props;
      if(needHonest){
        let params = {
          replyId: id,
          applicantOID,
          jobId
        };
        baseService.getHonestEvent(params).then(res => {
          res.data.id && honestEvent.filter(item => item.id === res.data.id).length === 0 && honestEvent.push(res.data);
          this.setState({honestEvent},() => {
            this.reasonInput.focus()
          });
        });
      }
    })
  };

  //审批意见输入
  onReasonChange = (e) => {
    this.setState({
      inputError: e.target.value.length > 500,
      errorMessage : messages('common.max.characters.length', {max: 500})
    })
  };

  //确认新增的快捷回复
  handleInputConfirm = () => {
    let values = this.props.form.getFieldsValue();
    if (values.quickReplyTxt) {
      if(values.quickReplyTxt.trim() && values.quickReplyTxt.trim().length <= 500) {
        this.setState({ loading: true });
        let url='/api/quick/reply';
        let param = {reply: values.quickReplyTxt.trim()};
        if(this.props.audit){
          url='/api/audit/quick/reply';
          param={
            reply: values.quickReplyTxt.trim(),
            tenantId: this.props.company.tenantId,
            type: 2000,
            status: 1000,
            setOfBooksId: this.props.company.setOfBooksId,
            userOid: this.props.user.userOID
          };
        }
        httpFetch.post(`${config.baseUrl}${url}`, param).then(res => {
          if(res.status === 200) {
            this.closeInputModal();
            this.getQuickTags();
            message.success(messages("common.operate.success")/*操作成功*/);
          }
        }).catch(() => {
          this.setState({ loading: false });
          message.error(messages('common.error1'));
        });
      } else {
        message.error(messages('common.max.characters.length', {max: 500}));
      }
    } else {
      message.error(messages('common.please.input'));
    }
  };

  //删除快捷回复标签
  handleDeleteTag = (e, item) => {
    e.stopPropagation();
    this.setState({ loading: true });
    let url='/api/quick/reply';
    let param = {quickReplyOIDs: item.quickReplyOID};
    if(this.props.audit){
      url='/api/audit/quick/reply';
      param = {id: item.id };
    }
    httpFetch.delete(`${config.baseUrl}${url}`, param ).then(res => {
      let isSuccess = this.props.audit ? res.data.rows : true;
      if(res.status === 200 && isSuccess) {
        this.getQuickTags();
        message.success(messages('common.delete.success', {name: ''}))
      }else{
        this.setState({ loading: false });
        message.error(messages('common.operate.filed'))  //操作失败
      }
    }).catch(e => {
      this.setState({ loading: false });
      message.success(`${messages('common.operate.filed')}，${e.response.data.message}`)
    })
  };

  handleFastReplyEdit =() => {
    let fastReplyEdit = this.state.fastReplyEdit;
    this.setState({ fastReplyEdit: !fastReplyEdit })
  };

  //审批通过
  handleApprovePass = () => {
    console.log('-----handleApprovePass-----')
    let values = this.props.form.getFieldsValue();
    const { additionalItems, priceAuditor, honestEvent } = this.state;
    const { needApplicantConfirm } = this.props;
    if(values.reason && values.reason.length > 500) return;
    /**
     * handleApprovePass(通过原因，加签人，是否需要价格审核)
     */
    if(this.props.needHonest){
      this.props.handleApprovePass(needApplicantConfirm ? 'CP:' : values.reason, honestEvent, additionalItems, priceAuditor);
    }else{
      this.props.handleApprovePass(needApplicantConfirm ? 'CP:' : values.reason, additionalItems, priceAuditor);
    }
  };

  //审批驳回
  handleApproveReject = () => {
    console.log('-----handleApproveReject-----')
    let values = this.props.form.getFieldsValue();
    const { needApplicantConfirm } = this.props;
    if(values.reason && values.reason.length > 500) return;
    // 驳回意见输入框需调整为非必填
    // https://pmo.mcd.com.cn/jira/browse/TES-1710
    // needApplicantConfirm（是否需要确认） 是一期用到的， 保留相关逻辑
    if ((!values.reason||!values.reason.trim()) && this.props.needReason && !needApplicantConfirm) {
      this.setState({
        inputError: true,
        errorMessage : messages('components.key411'/*请输入驳回意见*/)
      });
      if (this.state.additionalItems.length) {
        message.error(messages('components.key411'/*请输入驳回意见*/))
      }
    } else {
      this.setState({ inputError: false });
      const { additionalItems, honestEvent } = this.state;
      if(this.props.needHonest){
        this.props.handleApproveReject(needApplicantConfirm ? 'CR:' : values.reason, honestEvent, additionalItems);
      }else{
        this.props.handleApproveReject(needApplicantConfirm ? 'CR:' : values.reason, additionalItems);
      }
    }
  };

  //审批跳过
  handelApproveSkip = () => {
    this.setState({
      skipLoading: true,
      showAdminSkipModal: true
    });
  };

  //催办
  handelApprovePress = () =>{
    let entity = this.props.entities
    this.setState({ disablePress:true });
    let params ={
      "approverOID": entity.approverOID,
      "entityOID": entity.entityOID,
      "entityType": entity.entityType,
      applicantOID: entity.applicantOID,
      businessCode: entity.businessCode,
      formOID: entity.formOID
    }
    adminApproveListService.postPressMessage(params)
      .then(res=>{
        if(res.data){
          message.info(messages('components.key746')/*已向审批人发出催办消息*/);
          setTimeout(() => {
            // dataSource[index].hasClicked = false;
            this.setState({ disablePress:false })
          }, 3000)
        }
      }).catch(e => {
      this.setState({ disablePress:false })
      // this.setState({loading: false});
      message.error(`${e.response.data.message}`)
    });
  }

  afterClose = res => {
    this.setState({
      skipLoading: false,
      showAdminSkipModal: false,
    });
    this.props.handleApproveSkip(res);
  };

  //审核通知
  handleAuditNotice = () => {
    let values = this.props.form.getFieldsValue();
    if(values.reason && values.reason.length > 500) return;
    if (!values.reason||!values.reason.trim()) {
      this.setState({
        inputError: true,
        errorMessage : messages('components.key412'/*请输入通知内容*/)
      })
    } else {
      this.setState({ inputError: false });
      this.props.handleAuditNotice(values.reason)
    }
  };

  //返回
  goBack = () => {
    localStorage.setItem('isBackFinance', true)
    if (this.props.goBack) {
      this.props.goBack()
    } else {
      this.context.router.push(this.props.backUrl)
    }
  };

  //点击【更多】里的按钮
  handleClickMoreItem = (item) => {
    switch (item.key) {
      case 'additional':
        return this.setState({showAdditionalSelector: true});
      case 'noticeBtn':
        return this.handleAuditNotice();
      case 'auditCheck':
        return this.props.handleAuditCheck();
      case 'print':
        return this.props.handleApprovePrint();
      case 'check-invoice':
        return this.props.handleClickMore('check-invoice');
      case 'hangUp':
        return this.props.handleApproveHangUp();
      case 'autoAudit':
        return this.props.handleAutoAudit();
      case 'printCertificate':
        return this.props.handlePrintCertificate();
      case 'approveTransfer':
        return this.setState({transferVisible: true});
      default:
        return undefined
    }
  };

  //选择加签人
  handleSelectAddition = (rows) => {
    let additionalNames = [];
    let additionalItems = [];
    rows.result.map(item => {
      additionalNames.push(item.fullName);
      additionalItems.push(item);
    });
    this.setState({
      additionalNames,
      additionalItems,
      showAdditionalSelector: false
    }, () => {
      //先setState additionalItems 再打开加签弹框，这样人才能带入
      this.setState({additionalVisible: true});
    });
  };

  handlePriceView = (e) => {
    this.setState({ priceAuditor: e.target.checked })
  };

  //调整审批意见行数
  handleAutoSize = (isFocus) => {
    if (navigator.userAgent.indexOf("Edge") !== -1) {
      return;
    }
    if (isFocus) {
      if (this.timer) {
        clearTimeout(this.timer);
      }
      this.setState({
        isShowBigTextArea: true
      });
    } else {
      this.timer = setTimeout(()=>{
        this.setState({
          isShowBigTextArea: false
        });
      },1000);
    }
  };

  //移除信用事件
  removeEvent = (item) => {
    let { honestEvent } = this.state;
    honestEvent.map((record,index) => {
      record.id === item.id && (honestEvent[index] = undefined);
    });
    honestEvent = honestEvent.filter(temp => !!temp);
    this.setState({honestEvent});
  };

  //关闭审批转交弹框
  //isSuccess 是否是成功的转交
  handleCloseTransfer = (isSuccess) => {
    const { handleApproveTransfer } = this.props;
    this.setState({transferVisible: false});
    if (isSuccess && handleApproveTransfer) {
      handleApproveTransfer();
    }
  };

  //关闭加签的第二个弹框
  //isSuccess 是否是成功的返回
  //type backward 向后加签 forward 向前加签
  //params 向后加签要更新的参数，要刷新外层的加签人和审批意见
  handleCloseAdditional = (isSuccess, type, params) => {
    const { setFieldsValue } = this.props.form;
    const { handleApproveAdditional } = this.props;
    this.setState({additionalVisible: false});
    //处理向后加签的逻辑
    if (isSuccess && type === 'backward') {
      let additionalNames = [];
      let additionalItems = [];
      params.selectedData && params.selectedData.map(item => {
        additionalNames.push(item.fullName);
        additionalItems.push(item);
      });
      this.setState({
        additionalNames,
        additionalItems
      });
      setFieldsValue({ reason: params.quickTxt });
    }
    //处理向前加签的逻辑
    if (isSuccess && type === 'forward' && handleApproveAdditional) {
      handleApproveAdditional();
    }
  };

  //管理员转交
  handelAdminTransfer = () => {
    let values = this.props.form.getFieldsValue();
    if(values.reason && values.reason.length > 500) return;
    this.props.handleAdminTransfer(values.reason);
  };

  //审批通知
  handleApproveNotice = () => {
    console.log('-----handleApproveNotice-----')
    let values = this.props.form.getFieldsValue();
    const { additionalItems, priceAuditor, honestEvent } = this.state;
    const { needApplicantConfirm } = this.props;
    if(values.reason && values.reason.length > 500) return;
    /**
     * handleApproveNotice(通知原因，加签人，是否需要价格审核)
     */
    if(this.props.needHonest){
      this.props.handleApproveNotice(needApplicantConfirm ? 'CP:' : values.reason, honestEvent, additionalItems, priceAuditor);
    }else{
      this.props.handleApproveNotice(needApplicantConfirm ? 'CP:' : values.reason, additionalItems, priceAuditor);
    }
  };

  render() {
    const { getFieldDecorator } = this.props.form;
    const {
      audit, priceView, buttons, batchNumber, btnShowMode, width,jobId,
      invoiceNumber, moreButtons, customFormPropertyMap, customButtons
      , signCompanyOIDs, admin, from, isPrint, allLoading, entities,
      adminTransferDisabled, needApplicantConfirm, showNotice, showHandUp
    } = this.props;
    const {
      loading, tags, fastReplyEdit, inputVisible, inputValue, inputError,
      errorMessage, showAdditionalSelector, additionalNames, additionalItems,
      isShowBigTextArea, popoverVisible, showAdminSkipModal, honestEvent, transferVisible,
      additionalVisible
    } = this.state;
    const formItemLayout = {
      labelCol: { span: 6 },
      wrapperCol: { span: 18 }
    };
    const fastReplyTitle = (
      <div className="fast-reply-title">
        {messages('components.key413'/*快捷回复*/)}
        {this.props.audit ?
          <div className='info-message'>
            <Icon type='info' className='default-color-font default-color-border' style={{borderRadius: '50%',marginRight:'5px',fontSize:'14px'}}/>
            {messages('components.key414'/*账套下定义的快捷回复不可删除*/)}
          </div> :
          <div className='info-message'>
            <Icon
              type='info'
              className='default-color-font default-color-border'
              style={{
              borderRadius: '50%',
              marginRight: '5px',
              fontSize: '14px'}}
            />
            {messages('components.key705')/*管理员定义的快捷回复不可删除*/}
          </div>
        }
        <Icon type="close" className="edit" style={{fontSize: 21, marginLeft: 10, cursor: 'pointer'}} onClick={this.handleClosePopover} />
        {!fastReplyEdit && <a className="edit" onClick={this.handleFastReplyEdit}>{messages('common.edit')/*编辑*/}</a>}
        {fastReplyEdit && <a className="edit" onClick={this.handleFastReplyEdit}>{messages('components.key415'/*完成*/)}</a>}
      </div>
    );
    const fastReplyContent = (
      <div className="fast-reply">
        <Spin spinning={loading}>
          {tags.map(item => {
            let isEditItem=true;
            if(this.props.audit) {
              isEditItem = item.type !== 2001;
            }else{
              isEditItem = item.type !== 2002;
            }
            return (
              <CheckableTag key={item.id}
                            className={`fast-reply-tag ${fastReplyEdit && !isEditItem && 'disable-edit'}`}
                            color={'#000000'}
                            onChange={(checked) => this.onFastReplyChange(checked, item.id)}>{item.reply}
                {fastReplyEdit && isEditItem &&
                <a className="delete-tag" onClick={e => this.handleDeleteTag(e, item)}>&times;</a>}
              </CheckableTag>)
          })}
          {!inputVisible && !fastReplyEdit && <Button size="small"
                                                      type="dashed"
                                                      className="add-new-btn"
                                                      onClick={this.showTagInput}>+ {messages('components.key416'/*新增快捷回复*/)}</Button>}
        </Spin>
      </div>
    );
    const barLayout = {
      lg: 15,
      md: 24,
      sm: 24,
      xs: 24
    };
    const textLayout = {
      lg: 9,
      md: 24,
      sm: 24,
      xs: 24
    };
    let moreMenu = (
      <Menu onClick={this.handleClickMoreItem}>
        {moreButtons.map(type => {
          if (type === 'noticeBtn') {
            return <Menu.Item key="noticeBtn">{messages('common.notice')}</Menu.Item>
          }
          // if (type === 'hangUp') {
          //   return <Menu.Item key="hangUp">{messages('components.key892')/*暂挂*/}</Menu.Item>
          // }
          // if (type === 'additional') {
          //   return <Menu.Item key="additional">{messages('components.key417'/*加签*/)}</Menu.Item>
          // }
          if (type === 'approveTransfer') {
            return <Menu.Item key="approveTransfer">{messages('components.key947')/*转交*/}</Menu.Item>
          }
          if (type === 'auditCheck') {
            return <Menu.Item key="auditCheck">{messages('common.invoiceNumber',{total:invoiceNumber})}</Menu.Item>
          }
          if (type === 'print') {
            return <Menu.Item key="print">{messages('common.print')}</Menu.Item>
          }
          if (type === 'check-invoice') {
            return <Menu.Item key="check-invoice">{messages('components.key948')/*发票查验*/}</Menu.Item>
          }
          if (type === 'print-certificate') {
            return <Menu.Item key="printCertificate">{messages('components.key914')/*打印凭证*/}</Menu.Item>
          }
          if (type === 'autoAudit') {
            return <Menu.Item key="autoAudit">{messages('components.key915')/*自动审核*/}</Menu.Item>
          }
        })}
      </Menu>
    );
    let additionalMessage = (
      <Row>
        <Col span={21} className="info-col">{messages('components.key657',{arg1: additionalNames.length}/*单据通过后加签生效，加签 {arg1} 人*/)}：{additionalNames.join(', ')}</Col>
        <Col span={3} className="edit-col"><a onClick={() => {this.setState({ showAdditionalSelector: true })}}>{messages('common.edit')}</a></Col>
      </Row>
    );
    let chooserItem = deepFullCopy(chooserData['user']);
    if (signCompanyOIDs.length > 0) {
      chooserItem.url = `${config.baseUrl}/api/users/v3/search?corporationOID=${signCompanyOIDs}&companyOID=${signCompanyOIDs}`;
    }

    /**
     * 因为现在通知功能有问题，更多操作直接隐藏 https://pmo.mcd.com.cn/jira/browse/TES-1710
     */
    let showMoreMenu = false

    return (
      <div className="approve-bar" style={{ width }}>
        <Spin spinning={allLoading}>
          {admin && (
            <AdminSkip
              title={messages('setting.key881'/*跳转至*/)}
              entityOID={this.props.entities.entityOID}
              entityType={this.props.entities.entityType}
              onOk={this.handleOkTemp}
              afterClose={this.afterClose}
              visible={showAdminSkipModal}
            />
          )}
          <Row>
            {!needApplicantConfirm && <Col {...textLayout}>
              <Form layout={'inline'}>
                {jobId === "submitting" ? <p/>:
                <FormItem
                  validateStatus={inputError ? "error" : ""}
                  help={inputError ? errorMessage : ""}
                  className="approve-form">
                  <Popover trigger="click"
                           title={fastReplyTitle}
                           content={fastReplyContent}
                           visible={popoverVisible}
                           onVisibleChange={this.handleVisibleChange}
                           getPopupContainer={() => document.getElementsByClassName('approve-form')[0]}
                           overlayStyle={{maxWidth:'140%' , paddingLeft: window.ISIE9 ? 'calc(10% - 40px)' : 'calc(10vw - 40px)', maxHeight:'140px'}}>
                    {getFieldDecorator('reason')(

                      <TextArea placeholder={audit ? `${messages('components.key426'/*审核意见*/)}, ${messages('common.max.characters.length', {max: 500})}` : `${messages('components.key427'/*审批意见*/)}, ${messages('common.max.characters.length', {max: 500})}`}
                                ref={node => this.reasonInput = node}
                                style={{
                                  minHeight: isShowBigTextArea ? 136 : 32,
                                  height: 32,
                                  resize: 'none',
                                  marginBottom: 10,
                                  marginLeft: window.ISIE9 ? 20 : 0
                                }}
                                onBlur={(e) => this.handleAutoSize(false)}
                                onFocus={(e) => this.handleAutoSize(true)}
                                onChange={this.onReasonChange}/>
                    )}
                  </Popover>
                </FormItem>
                }
              </Form>
            </Col>}
            <Col {...barLayout} className="approve-btn" style={{paddingRight: '40px'}}>
              <Row>
                {!needApplicantConfirm && customButtons.map(button => (
                  <Button type={button.type} onClick={button.onClick} loading={button.loading}>{button.text}</Button>
                ))}
                {buttons.indexOf('pass') > -1 && !admin && (
                  <span>
                {batchNumber > 0 && btnShowMode === 'all'
                  ?
                  <Popconfirm onConfirm={this.handleApprovePass}
                              title={messages(needApplicantConfirm ? 'common.ok.number' : 'common.pass.number', {number: batchNumber})}>
                    <Button loading={this.props.passLoading}
                            className="pass-btn">{messages(needApplicantConfirm ? 'common.ok.all' : 'common.pass.all')}</Button>
                  </Popconfirm>
                  :
                  <Button type="primary"
                          onClick={this.handleApprovePass}
                          loading={this.props.passLoading}
                          htmlType="submit"
                          className="pass-btn">{messages(needApplicantConfirm ? 'components.key455' : 'common.pass')}</Button>
                }
                    {!needApplicantConfirm && priceView && (
                      <Checkbox onChange={this.handlePriceView}>{messages('components.key428'/*价格审核*/)}</Checkbox>
                    )}
              </span>
                )}
                {buttons.indexOf('pass') > -1 && admin && (
                  <span>
                               <Button type="primary"
                                       onClick={this.handleApprovePass}
                                       loading={this.props.passLoading}
                                       htmlType="submit"
                                       className="pass-btn">{batchNumber > 0 ? messages('components.key658', {arg1: batchNumber}/*直接通过{arg1}条*/) : messages('components.key429'/*直接通过*/)}</Button>
                          </span>
                )}
                {
                  admin && buttons.indexOf('skip') > -1 && <Button onClick={this.handelApproveSkip}
                                                                   loading={this.state.skipLoading}
                                                                   className="notice-btn"
                                                                   type="primary">{messages('components.key430'/*跳转*/)}</Button>
                }
                {admin && buttons.indexOf('transfer') > -1 && (
                  <Button onClick={this.handelAdminTransfer} type="primary" disabled={adminTransferDisabled}>
                    {messages('components.key947')/*转交*/}
                  </Button>
                )}
                {buttons.indexOf('reject') > -1 && !admin && (
                  batchNumber > 0 && btnShowMode === 'all'
                    ?
                    <Popconfirm onConfirm={this.handleApproveReject}
                                title={messages(needApplicantConfirm ? 'common.refuse.number' : 'common.reject.number', {number: batchNumber})}>
                      <Button loading={this.props.rejectLoading}
                              className="reject-btn">{messages(needApplicantConfirm ? 'common.refuse.all' : 'common.reject.all')}</Button>
                    </Popconfirm>
                    :
                    <Button loading={this.props.rejectLoading}
                            onClick={this.handleApproveReject}
                            htmlType="submit"
                            className="reject-btn">{messages(needApplicantConfirm ? 'setting.key442' : 'common.reject')}</Button>
                )}
                {
                  admin && buttons.indexOf('press') > -1 && <Button onClick={this.handelApprovePress}
                                                                    disabled={this.state.disablePress}
                                                                    className="notice-btn"
                                                                    type="primary">{messages('components.key747')/*催办*/}</Button>
                }
                {buttons.indexOf('reject') > -1 && admin && (
                  <Button loading={this.props.rejectLoading}
                          onClick={this.handleApproveReject}
                          htmlType="submit"
                          className="reject-btn">{batchNumber > 0 ? messages(needApplicantConfirm ? 'common.refuse.number' : 'common.reject.number', {number: batchNumber}) : messages(needApplicantConfirm ? 'setting.key442' : 'common.reject')}</Button>
              )}
              {!needApplicantConfirm && (audit || isPrint) && buttons.indexOf('print') > -1 && (
                <Button loading={this.props.printLoading} type="primary" className="notice-btn"
                        onClick={this.props.handleAuditPrint}>{batchNumber > 0 ? messages('common.print.number', {number: batchNumber}) : messages('common.print')}</Button>
              )}
              {/* TES-1608 新的通知按钮 */}
              {showNotice && <Button onClick={this.handleApproveNotice}
                      className="notice-btn"
                      type="primary">{messages('common.notice')/* 通知 */}</Button>}
              {/* TES-1746 新的暂挂按钮 */}
              {/* https://pmo.mcd.com.cn/jira/browse/TES-2132 隐藏暂挂 */}
              {showHandUp && false && <Button onClick={this.props.handleApproveHangUp}
                      className="notice-btn"
                      type="primary">{messages('components.key892')/*暂挂*/}</Button>}
              {!needApplicantConfirm && !!moreButtons.length && showMoreMenu && (
                <Dropdown overlay={moreMenu} placement="topCenter">
                  <Button>{messages('common.more.operate')}<Icon type="up"/></Button>
                </Dropdown>
              )}
              {(this.props.backUrl || this.props.goBack) &&
              <Button className={needApplicantConfirm ? "" : "back-btn"} onClick={this.goBack}>{messages("common.back")/*返回*/}</Button>}
            </Row>
            {
              // honestEvent.length > 0 && isShowBigTextArea && (<Row className={'approve-bar-honest'}>
              //   <Col span={4}  style={{textAlign:'center'}}>
              //     <span>{messages('components.key706')/*信用事件*/}:</span>
              //   </Col>
              //   <Col span={20}>
                  // <div>
                  // {
                  //   honestEvent.map(item => {
                  //     let result = item.changeScore;
                  //     item.operationType === 1001 && (result = `+${result}`);
                  //     item.operationType === 1002 && (result = `-${result}`);
                  //     item.operationType === 1003 && (result = `${item.changeRank}`);
                  //     item.operationType === 1004 && (result = `${item.changeRank}`);
                  //     let color = (item.operationType === 1001 || item.operationType === 1003) ? 'green-font' : 'red-font';
                  //     return (
                  //       <span className="honest-event">
                  //         <span style={{padding: '0px 10px',width:'100px',textAlign:'center',overflow:'hidden',textOverflow:'ellipsis',whiteSpace:'nowrap'}}>
                  //           <Popover placement="topLeft" content={item.ruleCondition}>
                  //             {item.ruleCondition}
                  //           </Popover>
                  //         </span>
                //           <span className={color}>
                //             {item.operationType === 1003 && <Icon type={'arrow-up'}/>}
                //             {item.operationType === 1004 && <Icon type={'arrow-down'}/>}
                //             {result}
                //             <Icon type={'close-circle'} className={'close'} onClick={() => this.removeEvent(item)}/>
                //           </span>
                //         </span>
                //           )
                //         })
                //       }
                //     </div>
                //   </Col>
                // </Row>)
              }
            </Col>
          </Row>
          {additionalNames.length > 0 && (
            <Row className="additional-alert-info">
              <Col {...barLayout}>
                <Popover content={additionalNames.join(', ')}>
                  <input style={{ position: 'absolute', top: '-9999vh', left: 0, zIndex: -1 }}/>
                  <Alert message={additionalMessage} type="info" />
                </Popover>
              </Col>
            </Row>
          )}
        </Spin>

        {/*用于加签人员选择，可多选*/}
        <ListSelector
          visible={showAdditionalSelector}
          selectorItem={chooserItem}
          showDetail
          labelKey="fullName"
          selectedData={additionalItems}
          extraParams={{roleType: 'TENANT'}}
          onOk={this.handleSelectAddition}
          onCancel={() => this.setState({ showAdditionalSelector: false })}
        />
        <Modal title={messages('components.key416'/*新增快捷回复*/)} visible={inputVisible} onCancel={this.closeInputModal} maskClosable={false} destroyOnClose={true}
               footer={[
                 <Button key="back" onClick={this.closeInputModal}>{messages('common.cancel')/*取消*/}</Button>,
                 <Button key="submit" htmlType="submit" type="primary" loading={loading} onClick={this.handleInputConfirm}>{messages('common.ok')/*确定*/}</Button>
               ]}
        >
          <Form>
            <FormItem>
              {getFieldDecorator('quickReplyTxt', {
                initialValue: ''
              })(
                <TextArea placeholder={messages('common.max.characters.length', {max: 500})}
                          rows={6}
                          style={{resize: 'none'}}/>
              )}
              <div style={{textAlign: 'right'}}>
                {this.props.form.getFieldValue('quickReplyTxt').trim().length} / 500
              </div>
            </FormItem>
          </Form>
        </Modal>

        {moreButtons.indexOf('approveTransfer') > -1 && (
          <ApproveTransfer
            transferVisible={transferVisible}
            onClose={this.handleCloseTransfer}
            entities={entities}
            customFormPropertyMap={customFormPropertyMap}
          />
        )}
        {/*向前加签*/}
        {moreButtons.indexOf('additional') > -1 && (
          <ApproveAdditional
            additionalVisible={additionalVisible}
            onClose={this.handleCloseAdditional}
            entities={entities}
            customFormPropertyMap={customFormPropertyMap}
            selectedData={additionalItems}
            quickTxt={this.props.form.getFieldsValue().reason}
          />
        )}
      </div>
    )
  }
}

ApproveBar.propTypes = {
  handleApprovePass: React.PropTypes.func, //审批通过方法
  handleApproveSkip: React.PropTypes.func, //审批跳过方法
  handleApproveReject: React.PropTypes.func, //审批驳回方法
  handleAuditNotice: React.PropTypes.func,  //审核通知方法
  handleAuditPrint: React.PropTypes.func,  //审核打印方法
  handleAuditCheck: React.PropTypes.func,//重新查验发票方法
  handleApprovePrint: React.PropTypes.func, //审批中打印
  handleApproveHangUp: React.PropTypes.func, //审批中暂挂
  handleApproveTransfer: React.PropTypes.func, //审批转交
  handleApproveAdditional: React.PropTypes.func, //审批向前加签
  handleAdminTransfer: React.PropTypes.func, //管理员转交
  adminTransferDisabled: React.PropTypes.bool, //管理员转交按钮disabled
  handleAutoAudit: React.PropTypes.func, //自动审核按钮
  handlePrintCertificate: React.PropTypes.func, //打印凭证
  customButtons: React.PropTypes.array,
  passLoading: React.PropTypes.bool, //审批通过按钮loading
  rejectLoading: React.PropTypes.bool, //审批通过按钮loading
  noticeLoading: React.PropTypes.bool,  //审核通知按钮loading
  printLoading: React.PropTypes.bool,  //审核打印按钮loading
  checkLoading: React.PropTypes.bool, //查验发票按钮loading
  backUrl: React.PropTypes.string, //点击"返回"按钮跳转到的页面
  audit: React.PropTypes.bool,  //是否为审核
  isHidePreAdditional: React.PropTypes.bool, //是否隐藏向前加签 审核隐藏 审批不隐藏
  isPrint: React.PropTypes.bool,//是否可打印
  batchNumber: React.PropTypes.number,  //批量数量
  buttons: React.PropTypes.array,  //显示的按钮，不传则都显示
  btnShowMode: React.PropTypes.string, //通过／驳回按钮的显示文案，不传的时候显示'通过'，'驳回'，如果传'all'，则显示'全部通过'，'全部驳回'
  priceView: React.PropTypes.bool,  //是否需要加价格审核
  width: React.PropTypes.any, //宽度
  moreButtons: React.PropTypes.array, //"更多"里需要显示的按钮，不传则都不显示: additional(加签)
  invoiceNumber: React.PropTypes.number, //为查验的发票数量
  signCompanyOIDs: React.PropTypes.array,//加签人的公司范围
  admin: React.PropTypes.bool, //是否是管理员直接审批
  entities:React.PropTypes.object,//审批跳转所需字段
  needHonest: React.PropTypes.bool, //是否需要信用事件
  needReason: React.PropTypes.bool, // 驳回意见是否必填，默认必填
  applicantOID: React.PropTypes.string, //申请人OID
  handleClickMore: React.PropTypes.func,
  allLoading: React.PropTypes.bool,
  jobId: React.PropTypes.string,//jobId
  needApplicantConfirm: React.PropTypes.bool, //是否需要确认
  showNotice: React.PropTypes.bool, // 是否显示通知按钮
};

ApproveBar.defaultProps = {
  handleApprovePass: () => {},
  handleApproveReject: () => {},
  handleAuditNotice: () => {},
  handleAuditPrint: () => {},
  handleAuditCheck: () => {},
  handleApprovePrint: () => {},
  handleApproveHangUp: () => {},
  handleApproveTransfer: () => {},
  handleApproveAdditional: () => {},
  handleAdminTransfer: () => {},
  handlePrintCertificate: () => {},
  customButtons: [],
  passLoading: false,
  rejectLoading: false,
  noticeLoading: false,
  printLoading: false,
  audit: false,
  isHidePreAdditional: false,
  checkLoading: false,
  batchNumber: 0,
  btnShowMode: '',
  invoiceNumber: 0,
  adminTransferDisabled: false,
  //transfer 不放在默认的buttons里
  buttons: ['pass', 'reject', 'notice', 'print', 'skip', 'press'], //这里的transfer是管理员转交，审批转交请用moreButtons里的转交
  priceView: false,
  width: window.ISIE9 ?
    (ApproveBar.propTypes.backUrl ? 'calc(100% - 206px)' : '100%') : '100%',
  moreButtons: [],
  signCompanyOIDs: [],
  admin: false,
  entities:{},
  isPrint: false,
  needHonest: false,
  needReason: true,
  handleClickMore: () => {},
  allLoading: false,
  jobId: null,
  needApplicantConfirm: false,
  showNotice: false
};

ApproveBar.contextTypes = {
  router: React.PropTypes.object
};

const wrappedApproveBar = Form.create(mapStateToProps)(ApproveBar);

function mapStateToProps(state) {
  return {
    user: state.login.user,
    company: state.login.company
  }
}

export default connect(mapStateToProps)(wrappedApproveBar);

